/* eslint-disable */

import { Form } from '@ant-design/compatible';

import '@ant-design/compatible/assets/index.css';

import { Row, Col, Input, Select } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import React, { PureComponent } from 'react';

import { TableC, ExportC } from '../../../../comps';
import config from '../../../../comps/business/tradingMarket/config';
import SetColumns from '../common/SetColumns';
import style from '../index.less';

@Form.create()
@connect(({ tansactionRecordquiryM, loading }) => ({
  tansactionRecordquiryM,
  loading: loading.effects['tansactionRecordquiryM/bondTable'],
}))
export default class Bond extends PureComponent {
  constructor(props) {
    super(props);
    this.scrollx = 0;
    this.newColumns = [];
    this.state = {
      search: {},
      columns: [],
      dataSource: [],
      page: 1,
      pageSize: 20,
      total: 0,
      account: {},
      treeData: [],
      checkedKeys: [],
      scrollx: 0,
      sortedInfo: null, // 排序对象
      orderByField: null, // 按某列排序
      order: null, // 升序降序
      newSearch: {},
    };
  }

  UNSAFE_componentWillMount() {
    const { dispatch } = this.props;
    // 债券默认查表头信息
    dispatch({
      type: 'tansactionRecordquiryM/queryShowCol',
      payload: {
        type: 'BOND_FLOW',
      },
      callback: () => {},
    });

    dispatch({
      type: 'tansactionRecordquiryM/getJysc',
    });
    dispatch({
      type: 'tansactionRecordquiryM/getZqJyfx',
    });
  }

  // eslint-disable-next-line react/no-deprecated
  UNSAFE_componentWillReceiveProps(nextProps) {
    const init = !this.props.args ? '' : JSON.stringify(this.props.args);
    const initN = !nextProps.args ? '' : JSON.stringify(nextProps.args);

    if (init != initN) {
      this.setState(
        {
          search: nextProps.args,
        },
        () => {
          this.getTableData();
        },
      );
    }
  }

  // 分页切换
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    let newOrder = '';
    sorter.order == 'descend' ? (newOrder = 'desc') : sorter.order == 'ascend' ? (newOrder = 'asc') : (newOrder = '');
    this.setState(
      {
        page: current,
        pageSize,
        sortedInfo: sorter,
        order: newOrder,
        orderByField: sorter.columnKey,
      },
      () => {
        this.getTableData('pageChange');
      },
    );
  };

  // 查询表格数据
  getTableData = (type, jyfx1, zqJysc1) => {
    const {
      form: { getFieldValue },
    } = this.props;
    const { dispatch } = this.props;
    const { order, orderByField, page, pageSize, search } = this.state;
    const sortedInfo = this.state.sortedInfo ? this.state.sortedInfo : {};
    // eslint-disable-next-line max-len
    if (
      Object.keys(sortedInfo).length &&
      sortedInfo.columnKey != 'tradingcode' &&
      sortedInfo.columnKey != 'parValueTotal' &&
      sortedInfo.columnKey != 'dealAmountTotal' &&
      sortedInfo.columnKey != 'dealValue' &&
      sortedInfo.columnKey != 'dealFullPrice' &&
      sortedInfo.columnKey != 'dealRate' &&
      sortedInfo.columnKey != 'exerciseDealRate' &&
      sortedInfo.columnKey != 'totalDealValueTotal'
    )
      return; // 阻止非排序列调用

    const params = {};
    params.pageSize = pageSize;
    if (type != 'pageChange') {
      // 点击查询按钮 重置页码
      this.setState({
        page: 1,
      });
      params.page = 1;
    } else {
      // 点击页码切换时候调用
      params.page = page;
    }

    const search2 = {};
    const issuer = getFieldValue('issuer');
    const jyfx = getFieldValue('jyfx');
    const zqJysc = getFieldValue('zqjysc');

    if (issuer) {
      search2.issuer = issuer;
    }

    if (jyfx1 != 1) {
      if (jyfx1) {
        search2.jyfx = jyfx1;
      } else {
        search2.jyfx = jyfx;
      }
    }

    if (zqJysc1 != 1) {
      if (zqJysc1) {
        search2.zqJysc = zqJysc1;
      } else {
        search2.zqJysc = zqJysc;
      }
    }

    const newSearch = Object.assign(search, search2);
    this.setState({
      newSearch,
    });
    // 列表数据
    dispatch({
      type: 'tansactionRecordquiryM/bondTable',
      payload: {
        ...params,
        ...search,
        ...search2,
        order,
        orderByField,
      },
      callback: (res) => {
        res.data &&
          res.data.map((item, key) => {
            item.key = key;
          });
        this.setState({
          dataSource: res.data,
          total: res.total,
        });
      },
    });
  };

  handleJyfxSelect = (e) => {
    this.getTableData(0, e);
  };

  handleJyfxSelect2 = (e) => {
    if (e == undefined) {
      this.getTableData(0, 1);
    }
  };

  handleJyscSelect = (e) => {
    this.getTableData(0, 0, e);
  };

  handleJyscSelect2 = (e) => {
    if (e == undefined) {
      this.getTableData(0, 0, 1);
    }
  };

  issuerChange = () => {
    this.getTableData();
  };

  // 导出参数调整
  changeSearch() {
    const { search } = this.state;
    const newSearch = _.cloneDeep(search);
    if (newSearch && newSearch.cpCode) {
      newSearch.cpCode = newSearch.cpCode.join(',');
    }
    return newSearch;
  }

  render() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const {
      tansactionRecordquiryM: { columnsInfo, checkedKeysInfo, jyfx, jysc },
      loading,
    } = this.props;
    let { sortedInfo } = this.state;
    sortedInfo = sortedInfo || {};
    const formItemLayout = {
      labelCol: {
        xs: { span: 4, offset: 0 },
        sm: { span: 8, offset: 0 },
        md: { span: 8, offset: 0 },
        lg: { span: 8, offset: 0 },
        xl: { span: 7, offset: 0 },
        xxl: { span: 5, offset: 0 },
      },
      wrapperCol: {
        xs: { span: 18, offset: 0 },
        sm: { span: 14, offset: 0 },
        md: { span: 14, offset: 0 },
        lg: { span: 14, offset: 0 },
        xl: { span: 15, offset: 0 },
        xxl: { span: 17, offset: 0 },
      },
    };
    const columns = _.cloneDeep(columnsInfo[1].columns);
    this.newColumns = columns.filter((item) => item.display == true);
    if (this.newColumns && this.newColumns.length > 10) {
      const a = this.newColumns.length;
      this.scrollx = a * 150;
    } else {
      this.scrollx = 0;
    }

    this.newColumns.map((item) => {
      item.dataIndex = item.key;
      if (
        item.key == 'tradingcode' ||
        item.key == 'parValueTotal' ||
        item.key == 'dealAmountTotal' ||
        item.key == 'dealValue' ||
        item.key == 'dealFullPrice' ||
        item.key == 'dealRate' ||
        item.key == 'exerciseDealRate' ||
        item.key == 'totalDealValueTotal'
      ) {
        item.sorter = true;
        item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
      }

      if (item.key == 'parValueTotal' || item.key == 'totalDealValueTotal') {
        item.type = 'money';
      }
      if (item.key == 'fee') {
        item.type = 'money';
        item.toFixed = '2';
      }
      if (item.key == 'dealValue' || item.key == 'dealFullPrice' || item.key == 'netvaluation' || item.key == 'fullvaluationfinal') {
        item.type = 'money';
        item.toFixed = '4';
      }

      if (item.key == 'dealAmountTotal' || item.key == 'maturity') {
        item.type = 'number';
      }

      if (item.key == 'dealRate' || item.key == 'exerciseDealRate' || item.key == 'exerciseMaturity' || item.key == 'yield' || item.key == 'exerciseYield') {
        item.type = 'number';
        item.toFixed = '4';
      }
      item.toFixed = '4';
      if (item.key === 'settleMoney') {
        item.type = 'money';
        item.toFixed = '2';
      }
      if (item.key == 'categorycode') {
        item.render = (text) => {
          if (text == 1905) {
            return <div>是</div>;
          }
          if (text != 999999) {
            return <div>否</div>;
          }
        };
      }

      if (item.key == 'dataDt' || item.key == 'deliverDt') {
        item.render = (text) => {
          if (text != '--' && text) {
            return `${text.slice(0, 4)}-${text.slice(4, 6)}-${text.slice(6)}`;
          }
          return '--';
        };
      }

      if (item.key == 'jysc') {
        item.render = (text, record) => {
          if (record?.exchangecode) {
            const findvalue = config.filter((item) => item.value == record.exchangecode);
            if (findvalue && findvalue.length > 0) {
              return findvalue[0].title;
            }
            return '--';
          }
          return '--';
        };
      }
    });

    const childrenJyfx = jyfx.map((item) => <Option key={item.codeDesc}>{`${item.codeDesc}`}</Option>);
    const childrenJysc = jysc.map((item, i) => <Option key={item.codeDesc}>{`${item.codeDesc}`}</Option>);

    return (
      <div>
        <Row>
          <Col span={18} style={{ marginTop: '6px' }}>
            <Form>
              <Row>
                <Col span={8}>
                  <Form.Item label='发行人' {...formItemLayout}>
                    {getFieldDecorator('issuer', {})(<Input onBlur={this.issuerChange} />)}
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item label='交易方向' {...formItemLayout}>
                    {getFieldDecorator(
                      'jyfx',
                      {},
                    )(
                      <Select allowClear showSearch placeholder='请选择' optionFilterProp='children' onChange={this.handleJyfxSelect2} onSelect={this.handleJyfxSelect}>
                        {childrenJyfx}
                      </Select>,
                    )}
                  </Form.Item>
                </Col>

                <Col span={8}>
                  <Form.Item label='交易市场' {...formItemLayout}>
                    {getFieldDecorator(
                      'zqjysc',
                      {},
                    )(
                      <Select allowClear showSearch placeholder='请选择' optionFilterProp='children' onChange={this.handleJyscSelect2} onSelect={this.handleJyscSelect}>
                        {childrenJysc}
                      </Select>,
                    )}
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Col>

          <Col span={6}>
            <div style={{ width: `${(22 / 24) * 100}%`, display: 'flex', flexDirection: 'row-reverse' }}>
              <SetColumns type='1' parameter='BOND_FLOW' checkedKeysInfo={checkedKeysInfo} />
              <ExportC style={{ marginTop: '10px' }} url='api/v1/transactionLs/exprotBnd' search={this.changeSearch()} />
            </div>
          </Col>
        </Row>

        <div className={style.icon}>
          <TableC
            columns={this.newColumns || []}
            dataSource={this.state.dataSource || []}
            onChange={this.handleTableChange}
            current={this.state.page}
            pageSize={this.state.pageSize}
            total={this.state.total}
            scroll={{ x: this.scrollx }}
            selfScrollY
            loading={loading}
            rowKey='key'
          />
        </div>
      </div>
    );
  }
}
